<template>
  <view class="login">
    <image :src="vuex_imgPath+'/login_bg.png'" class="login-bg" />
    <view class="logo">
      <image :src="vuex_imgPath+'/newLogo.png'" />
    </view>
    <view class="login-btn">
      <view class="login-int">
        <view class="t-int">手机号码</view>
        <view class="login-int-box">
          <u-input
            v-model="phone"
            :maxlength="11"
            placeholder="请输入手机号"
            font-size="28rpx"
            placeholder-style="color: #999;font-size:24rpx;"
          />
        </view>
      </view>
      <view class="login-int">
        <view class="t-int">验证码</view>
        <view class="login-int-box">
          <view class="verode-box">
            <u-input v-model="code" placeholder="短信验证码" font-size="28rpx" placeholder-style="color: #999;font-size:24rpx;" />
          </view>
          <view class="verode" @click="getCode()">{{ getCodeName }}</view>
        </view>
      </view>
      <view class="login-btn">
        <!-- #ifdef H5 -->
        <button type="default" :plain="true" class="login-box login-org btn-noborder login-org-curr" @click="Login">立即登录</button>
        <!-- #endif -->
      </view>
    </view>
    <view class="privacy-radio">
      <u-checkbox-group v-model="flag" placement="row">
        <u-checkbox
          shape="circle"
          active-color="#FF5533"
          name="true"
        />
      </u-checkbox-group>
      <view class="radio-hint">
        我已阅读井同意
        <view @click="goWeb('agree')">《鑫方盛服务协议》</view>和
        <view @click="goWeb('pol')">《隐私政策》</view>
      </view>
    </view>
    <view class="login-other">
      <view v-if="isWeixin" class="login-box login-weixin" @click="onH5WeixinButtonClick()"><text class="font_family icon-WeChat_tongyong_1" />微信登录</view>
      <view class="login-box " @click="goPasswordLoginFn()"><text class="font_family icon-person_tongyong_1"></text>账号密码</view>
      <view class="hint">首次登录会自动注册新账号</view>
    </view>
    <u-popup :show="showPopVisible" :round="5" mode="bottom" height="420" @close="closePop">
      <RegisterPop
        :page-type="type"
        :callback-url="callbackUrl"
        :url-params="urlParams"
        :branch-data="registParams"
        @closePopFn="closePop"
      />
    </u-popup>
    <!-- #ifdef H5 -->
    <view>
      <view>
        <!--组件-->
        <slideVerify v-if="slideShowStatus" @seccess="slideYzSeccess" />
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import RegisterPop from '@/components/register-pop';
import { loginMixin } from '@/login/loginMixin';
import { mapInfo } from '@/common/getMapInfosMixin';
import '@/static/scss/login.scss';
import { getCode, codeLogin, traceless , getUserinfoByPc, wechatLoginV3, getWechatTokenByM,} from '@/api/login.js';
import { getLoginInfoFn, initSlide, tdkUrl } from '@/common/common'
import { getAuthCode } from '@/utils/login';
import slideVerify from '@/components/slide-verify.vue';

export default {
  name: 'McodeLogin',
  components: {
    RegisterPop,
    slideVerify
  },
  mixins: [loginMixin, mapInfo],
  data() {
    return {
      flag: false,
      showPopVisible: false,
      type: '',
      typePage: '',
      callbackUrl: '',
      urlParams: '',
      registParams: '',
      isWeixin: false,
      slideShowStatus: false,
      pageHeight: '',
      getCodeName: '获取验证码',
      codeFlag: true,
      phone: '',
      code: '',
      clicktime: true
    }
  },
  onShow() {
    console.log('我是登录111')
    //#ifdef H5
    //initSlide()
    // #endif
  },
  onLoad(option) {
    console.log('我是登222')

    const { type = '', callbackUrl = '', urlParams = '', registParams = '', typePage = '', typeDetail = '', productDetailSkucode = '' ,shareMemberId=''} = option
    this.type = type
    this.typePage = typePage
    this.callbackUrl = callbackUrl
    this.urlParams = urlParams
    this.typeDetail = typeDetail
    this.productDetailSkucode = productDetailSkucode
    this.shareMemberId =shareMemberId
    this.registParams = registParams ? JSON.parse(registParams) : ''

    //#ifdef H5
    if (this.typePage == 'h5' && this.vuex_loginStatus) {
      uni.reLaunch({ url: '/myAccount/giftCard/index' })
    }
    this.isWeixin = this.isWechat()
    this.getLocation()
    // #endif
  },
  methods: {
    goWeb(type) {
      if (type == 'pol') {
        uni.navigateTo({ url: `./pol` })
      } else {
        uni.navigateTo({ url: `./agree` })
      }
    },
    onLoginButtonClick() {
      if (!this.flag) {
        this.$u.toast('未勾选协议，请勾选')
        return
      }
      this.loginEvent(this.registParams, this.type, this.callbackUrl, this.urlParams ? JSON.parse(this.urlParams) : null,this.shareMemberId);
    },
    //m站 微信网页授权登录
    onH5WeixinButtonClick() {
      if (!this.flag) {
        this.$u.toast('未勾选协议，请勾选')
        return
      }
      if (this.typePage == 'h5') {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc8374f608503bb7a&redirect_uri=' + tdkUrl.develop + '/front/myAccount/giftCard/index&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
      } else {
       // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc8374f608503bb7a&redirect_uri=' + tdkUrl.develop + '/front/pages/myAccount/index&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'          //window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc8374f608503bb7a&redirect_uri=' + tdkUrl.develop + '/front/pages/myAccount/index&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
          if (this.typeDetail == 'detail' && this.productDetailSkucode != '') {
              const params =encodeURIComponent(  tdkUrl.develop + '/productsku/'+this.productDetailSkucode+'.html?productDetailSkucode='+this.productDetailSkucode+'&page=1&shareMemberId='+this.shareMemberId+'&typeDetail=detai')
              window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc8374f608503bb7a&redirect_uri='+params+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
              // window.location.href ='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc8374f608503bb7a&redirect_uri=' + tdkUrl.develop + '/productsku/'+this.productDetailSkucode+'.html?page=1&shareMemberId='+this.shareMemberId+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
            }else{
              window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc8374f608503bb7a&redirect_uri=' + tdkUrl.develop + '/front/pages/myAccount/index&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
            }
      }
    },
    //方法：用来判断是否是微信内置的浏览器
    isWechat() {
      return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === 'micromessenger';
    },
    goPasswordLoginFn() {
      console.log('m站登录账号密码跳转',this.urlParams)
      uni.navigateTo({
        url: `./passwordLogin?type=${this.type}&callbackUrl=${this.callbackUrl}&urlParams=${this.urlParams}&typePage=${this.typePage}&typeDetail=${this.typeDetail}&productDetailSkucode=${this.productDetailSkucode}&shareMemberId=${this.shareMemberId}`
      })
    },
    phoneFun(phones) {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phones)) {
        return false
      } else {
        return true
      }
    },
    tranClassFn(parame) {
      traceless({ nvcVal: parame }).then((res) => {
        this.resultTrace(res);
      }).catch(() => {
        // eslint-disable-next-line no-mixed-spaces-and-tabs
      })
    },
    resultTrace(res) {
      if (res.data == 200 || res.data == 100) {
        //验证通过
        this.successCode()
        return;
      }

      if (res.data == 400) {
        //验证不通过
        var ncoption = {
          // 声明滑动验证需要渲染的目标ID。
          renderTo: 'nc',
        }
        // 唤醒二次验证（滑动验证码）
        window.nvc.getNC(ncoption);
        this.slideShowStatus = true
        return;
      }

      if (res.data == 900) {
        //二次验证验证不通过
        console.log('验证失败', 3000);
        return;
      }

      if (res.data == 800) {
        //直接拦截
        console.log('您的账号存在异常，请联系在线客服！', 3000);
        return;
      }
    },
    getCode() {
      const _this = this

      if (!this.phoneFun(this.phone)) {
        this.$u.toast('请输入正确的手机号')
        return
      }
      if (!this.codeFlag) return
      // #ifdef H5
      // window.nvc.getNVCValAsync(function(nvcVal) {
      //   console.log('点击获取验证码掉无痕')
      //   if (_this.slideShowStatus == true) {
      //     _this.slideShowStatus = false
      //   }
      //   _this.tranClassFn(decodeURIComponent(nvcVal))
      // });
      this.successCode()
      // #endif
      // #ifdef MP-ALIPAY || MP-WEIXIN
      this.successCode()
    // #endif
    },

    successCode() {
      let timer = null
      const params = { phoneNumber: this.phone }
      const that = this
      getCode(params).then((res) => {
        if (res.errorCode == 0) {
          timer = that.countDownFn(60)
          this.$u.toast(`短信验证码已发送至${this.phone}`)
        } else {
          clearInterval(timer)
          this.getCodeName = `获取验证码`
          this.codeFlag = true
          this.$u.toast(res.msg)
        }
      })
    },
    countDownFn(num) {
      const timer = setInterval(() => {
        if (num > 0) {
          num--
          this.getCodeName = `${num}秒后重新获取`
          this.codeFlag = false
        } else {
          clearInterval(timer)
          this.getCodeName = `获取验证码`
          this.codeFlag = true
        }
      }, 1000)
      return timer
    },
    Login() {
      console.log(this.registParams);
      if (!this.phoneFun(this.phone)) {
        this.$u.toast('请输入正确的手机号')
        return
      }
      if (!this.code) {
        this.$u.toast('验证码不能为空')
        return
      }
      if (!this.flag) {
        this.$u.toast('未勾选协议，请勾选')
        return
      }
      const provider = this.vuex_provider;
      getAuthCode(provider, (loginRes) => {
        if (loginRes.code) {
          this.$u.vuex('vuex_login_code', loginRes.code)
        }
      })
      let registParams = {}
      registParams = (this.registParams && Object.keys(this.registParams).length > 0) ? this.registParams : this.vuex_sharePushmanCompanyInfo
      const { branchId = '', branchName = '', settleType } = registParams || {}
      const params = {
        phoneNumber: this.phone,
        verificationCode: this.code,
        inviteCode: uni.getStorageSync('inviteCode'),
        memberAscriptionId: branchId,
        memberAscriptionName: branchName,
        settleType: settleType || null,
        appFlag: 1 // "小程序和M站区分[0-小程序 1-M站]
      }
      if (this.vuex_mapAddress) {
        // 小程序新增登录/注册所在地信息
        const { provinceName, cityName, districtName } = this.vuex_mapAddress
        params.commonParamProvinceName = provinceName
        params.commonParamCityName = cityName
        params.commonParamDistrictName = districtName
      }
      codeLogin(params).then((res) => {
        if (res.errorCode == 0) {
          this.$u.vuex('vuex_accountInfo', res.data) //res.data
          this.$u.vuex('vuex_userInfo', res)
          getLoginInfoFn(res.data.memberId)
          // #ifdef H5
          const mySelectStation = JSON.parse(localStorage.getItem('my_select_station'));
          uni.$u.vuex('vuex_cityInfo', mySelectStation);
          // #endif
          this.$u.vuex('vuex_loginStatus', true)
          let paramStr = ''
          if (this.urlParams) {
            for (const urlParamsKey in this.urlParams) {
              paramStr += urlParamsKey + '=' + this.urlParams[urlParamsKey] + '&'
            }
          }
          if (this.type == 'order') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.type == 'my') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.type == 'ground') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.typePage == 'h5') {
            uni.reLaunch({ url: '/myAccount/giftCard/index' })
          } else if(this.type == 'pointsGoodsDetail'){
             this.urlParams =JSON.parse(this.urlParams)
            uni.reLaunch({ url: '/myAccount/pointsMall/pointsGoodsDetail?skuId='+this.urlParams.skuId+'&title=' + this.urlParams.title + '&exchangeType=' +this.urlParams.exchangeType})

          } else {
            // #ifdef MP-ALIPAY || MP-WEIXIN
            uni.reLaunch({ url: '/shopIndex/shopIndex' })
            // #endif
            // #ifdef H5
            if (this.typeDetail == 'detail' && this.productDetailSkucode != '') {
              window.location.href = `${tdkUrl.develop}/productsku/${this.productDetailSkucode}.html?page=1&shareMemberId=${this.shareMemberId}`
            }
            // #endif


          }
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    //接无痕验证收验证成功的值
    slideYzSeccess(data) {
      console.log('400时出现的滑块 当移动滑块成功之后返回')
      //会话ID（sessionId）、签名串（sig）、请求唯一标识（token）
      console.log(data.sessionId)
      console.log(data.sig)
      console.log(data.token)
      this.Login()
    },
  }
}
</script>

<style scoped lang="scss">
.login{
  padding-top: 50rpx;
  .logo{
    padding:46rpx 0 126rpx 4rpx;
    image{
      width:324rpx;
      height:74rpx;
    }
  }
  .welcome{
    padding: 156rpx 0 200rpx 2rpx;
    .text01{
      font-size: 48rpx;
      font-weight: bold;
    }
    .text02{
      font-size:40rpx;
    }
  }
}
.login-int-box {
  border: 2rpx solid $uni-grey-e2 !important;
  // #ifdef MP-ALIPAY
  /deep/ .u-input{
    padding-top: 8rpx!important;
  }
  // #endif
  /deep/ input {
    height:48rpx!important;
    line-height:48rpx!important;
  }
}
</style>
